<?php declare(strict_types=1);

namespace Zyucv7\Core\Web\Request;

class Uri {

    /**
     * 请求URI
     * 
     * @var string
     */
    private string $uri;

    public function __construct(array $server)
    {
        // 优先使用 REQUEST_URI
        if (isset($server['REQUEST_URI'])) {
            $this->uri = $server['REQUEST_URI'];
            return;
        }
        
        // 备用方案
        $uri = $server['SCRIPT_NAME'] ?? '/';
        if (isset($server['PATH_INFO'])) {
            $uri .= $server['PATH_INFO'];
        }
        if (isset($server['QUERY_STRING']) && $server['QUERY_STRING'] !== '') {
            $uri .= '?' . $server['QUERY_STRING'];
        }
        
        $this->uri = $uri;
    }
    
    /**
     * 获取请求URI
     * 
     * @return string
     */
    public function getUri(): string
    {
        return $this->uri;
    }

    /**
     * 获取请求路径（不包含查询字符串）
     * 
     * @return string
     */
    public function getPath(): string
    {
        $uri = $this->uri;
        $queryPos = strpos($uri, '?');
        return $queryPos !== false ? substr($uri, 0, $queryPos) : $uri;
    }

    /**
     * 获取查询字符串
     * 
     * @return string
     */
    public function getQueryString(): string
    {
        $queryPos = strpos($this->uri, '?');
        return $queryPos !== false ? substr($this->uri, $queryPos + 1) : '';
    }
    
}